import { Injectable, OnModuleDestroy } from '@nestjs/common';
import { createClient, RedisClientType } from 'redis';

@Injectable()
export class RedisService implements OnModuleDestroy {
  private client: RedisClientType;

  constructor() {
    // 创建 Redis 客户端
    this.client = createClient({
      url: process.env.REDIS_URL,
      password: process.env.REDIS_PASSWORD,
      // 可选的其他配置
      socket: {
        connectTimeout: 10000, // 连接超时时间
        reconnectStrategy: (retries) => Math.min(retries * 100, 3000), // 重连策略
      },
    });
    // 连接 Redis
    this.connect();

    // 错误处理
    this.client.on('error', (err) => {
      console.error('Redis 连接错误:', err);
    });
  }

  private async connect() {
    await this.client.connect();
  }

  // 模块销毁时断开连接
  async onModuleDestroy() {
    await this.client.quit();
  }

  // 设置键值对
  async set(key: string, value: string, ttl?: number) {
    if (ttl) {
      await this.client.setEx(key, ttl, value);
    } else {
      await this.client.set(key, value);
    }
  }

  // 获取值
  async get(key: string) {
    return await this.client.get(key);
  }

  // 删除键
  async del(key: string) {
    await this.client.del(key);
  }

  // 检查键是否存在
  async exists(key: string) {
    return await this.client.exists(key);
  }
}